<!DOCTYPE html>
<html>
<head>
    <title>音频切割</title>
    <script src="https://unpkg.com/wavesurfer.js"></script>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 先引入 Vue -->
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <style>
        #waveform {
            width: 600px;
            height: 200px;
            position: relative;
        }

        .block {
            margin-bottom: 20px;
        }
        .overlay {
            position: absolute;
            width: 600px;
            height: 200px;
            z-index: 100;
            border: 1px solid #0B102C;
            opacity: 0.3;
        }

    </style>
</head>
<body>


<div id="app">
    <!-- 音频波形展示容器 -->
    <div class="block">
        <div id="waveform">
            <canvas id="myCanvas" width="600" height="100" class="overlay"
                    style="border:1px solid #000000;">
            </canvas>
        </div>
    </div>

    <div class="block">
        <el-slider
                style="width: 600px"
                v-model="rangeValue"
                range
                show-stops
                @change="changeSlider"
                :max="1000">
        </el-slider>
    </div>

    <div class="block">
        <el-upload
                class="upload-demo"
                action="upload.php"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-success="uploadSuccess"
                :file-list="fileList">
            <el-button size="small" type="primary">点击上传音频文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传wav/mp3/ogg文件，且不超过100mb</div>
        </el-upload>
    </div>

    <div class="block">
        <el-button size="small" type="primary" @click="cutAudio">剪裁并导出</el-button>
    </div>

</div>

</body>
</html>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                divWidth: 600,
                overlayLeft: '50px',
                filePath: '',
                maxValue: 1000,
                audioDuration: 0,
                rangeValue: [1, 1000],
                wavesurfer: null,
                fileList: []
            };
        },
        mounted() {
            this.wavesurfer = WaveSurfer.create({
                container: '#waveform',
                waveColor: 'violet',
                progressColor: 'purple'
            });
            this.drawRect(0, 0, this.divWidth, 100)
        },
        methods: {
            drawRect(x, y, w, h) {
                var c = document.getElementById("myCanvas");
                var ctx = c.getContext("2d");
                ctx.clearRect(0, 0, c.width, c.height)
                ctx.fillStyle = "#FF0000";
                ctx.fillRect(x, y, w, 100);
            },
            cutAudio() {
                // 计算切割时间点
                this.$message.error('没有可以切割的文件');
                let duration = this.wavesurfer.getDuration();
                if(!duration){
                    return ;
                }
                this.$message('切割中，稍后导出...');
                let startTime = duration * parseFloat(this.rangeValue[0]) / this.maxValue;
                let endTime = duration * parseFloat(this.rangeValue[1]) / this.maxValue;
                $.ajax({
                    url: 'cut.php',
                    method: 'POST',
                    data: {start_time: startTime, end_time: endTime, filePath: this.filePath},
                    success: (res) => {
                        // 处理响应结果
                        let res1 = JSON.parse(res)
                        let a = document.createElement('a')
                        var filePath = res1.file_path
                        let path = filePath.lastIndexOf('/')
                        a.download = filePath.substr(path + 1)//设置下载的文件名
                        a.href = res1.file_path; // 设置图片的下载地址
                        a.click();//触发下载事件
                    },
                    error: (xhr, status, error) => {
                        // 处理错误
                        console.log('切割失败');
                        console.log(error);
                    }
                });
            },
            changeSlider(e) {
                let x = Math.ceil(this.rangeValue[0] / this.maxValue * this.divWidth)
                let tmpWidth = this.rangeValue[1] - this.rangeValue[0];
                let width = Math.ceil(tmpWidth / this.maxValue * this.divWidth)
                this.drawRect(x, 0, width, 100)
            },
            uploadSuccess(res, file, fileLis) {
                if(res.code ==500){
                    this.$message.error(res.msg);
                    this.fileList = [];
                    return;
                }
                this.wavesurfer.load(res.path);
                this.filePath = res.path
                this.audioDuration = this.wavesurfer.getDuration();
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePreview(file) {
                console.log(file);
            },
            beforeRemove(file, fileList) {
                return this.$confirm(`确定移除 ${file.name}？`);
            }
        }
    })


</script>
